/*
 * @Author: 黑白灰01 3193273703@qq.com
 * @Date: 2025-09-10 11:21:24
 * @LastEditors: 黑白灰01 3193273703@qq.com
 * @LastEditTime: 2025-09-10 11:24:20
 * @FilePath: /auth/src/core/filter/http-exception/http-exception.filter.ts
 * @Description: 异常过滤器
 * 
 * Copyright (c) 2025 by 3193273703@qq.com, All Rights Reserved. 
 */
import { ArgumentsHost, Catch, ExceptionFilter, HttpException } from '@nestjs/common';
import { Response } from 'express';

@Catch(HttpException)
export class HttpExceptionFilter implements ExceptionFilter {
  catch(exception: HttpException, host: ArgumentsHost) {
    const ctx = host.switchToHttp();
    const response = ctx.getResponse<Response>();
    const status = exception.getStatus();

    // 设置错误信息
    const message = exception.message
      ? exception.message
      : `${status >= 500 ? 'Service Error' : 'Client Error'}`;

    const errorResponse = {
      data: {},
      msg: message,
      code: status, // 使用实际的状态码而不是固定值-1
    };

    // 设置返回的状态码， 请求头，发送错误信息
    response.status(status);
    response.header('Content-Type', 'application/json; charset=utf-8');
    response.send(errorResponse);
  }
}
